package drds.plus.executor.cursor.cursor.impl.common;

import drds.plus.executor.cursor.cursor.ILimitFromToCursor;
import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.cursor.cursor.impl.SortingCursor;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.utils.Utils;
import drds.plus.util.GeneralUtil;
import drds.tools.Threads;

/**
 * 用于做limit操作
 */
public class LimitFromToCursor extends SortingCursor implements ILimitFromToCursor {

    private Long limitFrom = null;
    /**
     * 实际含义是偏移量。非limit to的概念。
     */
    private Long offset = null;
    private int count = 0;

    public LimitFromToCursor(ISortingCursor cursor, Long limitFrom, Long offset) throws RuntimeException {
        super(cursor, null, cursor.getOrderByList());
        this.limitFrom = limitFrom;
        this.offset = offset;
    }

    protected void init() throws RuntimeException {
        if (inited) {
            return;
        }
        /**
         * 跳过limit from
         */
        if (limitFrom != null && limitFrom != 0l) {
            long n = limitFrom;
            while (n != 0 && n-- > 0) {
                Threads.checkInterrupted();
                if (cursor.next() == null) {
                    break;
                }
            }
        }
        super.init();
    }

    public RowValues next() throws RuntimeException {
        init();
        count++;
        if (offset != null) {
            if (offset == 0l) {// limit To == 0 表示没有限制。
                return super.next();
                //[1][2]才有意义
            } else if (offset != null && count > offset) {// [1]表示当前已经取出的值>limit
                // to限定
                return null;
            } else {//[2] 表示当前已经取出的值<limit to限定。
                return super.next();
            }
        } else {
            return super.next();//offset==null表示没有限制。
        }

    }

    public String toString() {
        return toStringWithInden(0);
    }

    public String toStringWithInden(int inden) {
        StringBuilder sb = new StringBuilder();
        String tab = GeneralUtil.getTab(inden);
        sb.append(tab).append("【Limit cursor . from : ").append(limitFrom).append(" to :").append(offset).append("\n");
        Utils.printOrderByList(orderByList, inden, sb);
        sb.append(super.toStringWithInden(inden));
        return sb.toString();
    }

    public void beforeFirst() throws RuntimeException {
        inited = false;
        count = 0;
        super.beforeFirst();
    }

}
